package fr.mycompany.rce.ws.v1_0;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

public class MockRequestStrategy implements RequestStrategy {

	private static Logger log = LoggerFactory.getLogger(MockRequestStrategy.class);
	
	String fileName;
	
	public MockRequestStrategy(String fileName){
		this.fileName=fileName;
	}
	
	@Override
	public BK90L00Input createRequest(String input) {
		BK90L00Input bk90L00Input;
		bk90L00Input = getInXML(this.fileName);
		bk90L00Input.getDonneesCommEntree().getDonneesCommunesEntree().setCodPeridex(input);
		return bk90L00Input;

	}

	private BK90L00Input getInXML(String fileName) {

		String baseClassPath;
		JAXBContext jaxbContext;

		// Objet JAXB représentant la réponse retournee par le Web Service après
		// l'unmarshalisation
		JAXBElement<BK90L00Input> wsResponse;

		BK90L00Input bk90L00Input;
		baseClassPath = "";

		log.debug("Chemin du fichier XML : " + baseClassPath);

		ClassLoader classloader = Thread.currentThread().getContextClassLoader();
		String path = (new StringBuilder()).append(baseClassPath).append(fileName).append(".xml").toString();
		ClassPathResource xmlClientResource = new ClassPathResource(path, classloader);

		log.debug("Nom du fichier XML trouvé : " + path);

		InputStream xmlFileAsStream;
		try {
			xmlFileAsStream = xmlClientResource.getInputStream();

			// Unmarshall du fichier XML avec JAXB
			jaxbContext = JAXBContext.newInstance(new Class[] { BK90L00Input.class });
			jaxbContext.createUnmarshaller();
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			// unmarshaller.setEventHandler(new
			// DefaultValidationEventHandler());
			wsResponse = unmarshaller.unmarshal(new StreamSource(xmlFileAsStream), BK90L00Input.class);
			bk90L00Input = (BK90L00Input) wsResponse.getValue();

			org.springframework.util.Assert.notNull(bk90L00Input);
			log.info(bk90L00Input.toString());

		} catch (IOException ioe) {
			log.error("Pas de fichier " + xmlClientResource + " trouvé - " + ioe);
			return null;
		} catch (JAXBException jaxe) {
			throw new RuntimeException((new StringBuilder()).append("can NOT build bk90L00Input for fileName '").append(fileName).append("'").toString(), jaxe);
		}
		
		return bk90L00Input;

	}

}
